package com.jiangli.scheduler;


import com.github.pagehelper.Page;
import com.jiangli.entity.Dish;
import com.jiangli.entity.DishRating;
import com.jiangli.mapper.DishRatingMapper;
import com.jiangli.service.impl.DishServiceImpl;
import com.jiangli.vo.DishRatingAdminVO;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
public class DishRatingReflash {
    private final DishServiceImpl dishService;
    private final DishRatingMapper dishRatingMapper;
    public DishRatingReflash(DishServiceImpl dishService,
                             DishRatingMapper dishRatingMapper)
    {
        this.dishService = dishService;
        this.dishRatingMapper = dishRatingMapper;
    }
    @Scheduled(cron = "0 0 4 * * ?")
    public void syncTask() {
        List<Dish> dishList = dishService.getAllDishesWithCache();
        for(Dish dish : dishList)
        {
            Long id = dish.getId();
            List<DishRating> dishRatings = dishRatingMapper.getDishRating(id);
            double total = 0;
            if(!dishRatings.isEmpty())
            {
                for(DishRating dishRating : dishRatings)
                {
                    total += dishRating.getScore();
                }
                double rate = total / dishRatings.size();
                Dish dish1 = new Dish();
                dish1.setId(id);
                dish1.setDishRating((float) rate);
                dish1.setRatingCount((long) dishRatings.size());
                dishService.updateDish(dish1);
            }
        }
    }
}
